import { reqLogin, reqLogout } from "@/api/user";

// vuex模块
export default {
  namespaced: true,
  state: {
    name: localStorage.getItem("name"),
    token: localStorage.getItem("token"),
  },
  actions: {
    async login({ commit }, { phone, password }) {
      const user = await reqLogin(phone, password);
      commit("LOGIN", user);
    },
    async logout({ commit }) {
      await reqLogout();
      commit("LOGOUT");
    },
  },
  mutations: {
    LOGIN(state, user) {
      localStorage.setItem("token", user.token);
      localStorage.setItem("name", user.name);

      state.name = user.name;
      state.token = user.token;
    },
    LOGOUT(state) {
      localStorage.removeItem("token");
      localStorage.removeItem("name");

      state.name = "";
      state.token = "";
    },
  },
};
